import angr
import sys
import logging
import os

def main(argv):
    bin_path = argv[1]
    p = angr.Project(bin_path,auto_load_libs=False)

    cfg = p.analyses.CFGFast()

    functions = p.kb.functions

    logger = logging.getLogger()
    #logging.basicConfig(filename='function_info.log',filemode='w',level=logging.INFO)
    logger.setLevel(logging.INFO)

    logfile = './function_info.txt'
    file_handler = logging.FileHandler(logfile,mode='w')
    file_handler.setLevel(logging.DEBUG)

    log_formatter = logging.Formatter('%(message)s')
    file_handler.setFormatter(log_formatter)

    logger.addHandler(file_handler)

    for function in functions.values():
       # block_addrs = list(function.block_addrs)
       # block_addrs.sort()
       # end_address = block_addrs[-1] + p.factory.block(block_addrs[-1]).size
       # end_address = max(block.addr + block.size - 1 for block in function.blocks)
        end_addresses = function.endpoints 
       # logging.info("Func:{},start addr:{}".format(function.name,hex(function.addr)))
        logging.info("Func: %s, start address: 0x%x", function.name, function.addr)
        logging.info("  End addresses:")
        for address in end_addresses:
            block = p.factory.block(address.addr)
           # logging.info(f"   End Block:{block}")
           # logging.info(f"   Code:\n{block.capstone}\n")
            logging.info("    Block: %s", block)
            logging.info("    Code:\n%s\n", block.capstone)

    logger.removeHandler(file_handler)
    file_handler.close()


if __name__ == '__main__':
    main(sys.argv)
